package com.app.hmst.main;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.app.hmst.model.IndicatorResultVO;
import com.roscopeco.ormdroid.Entity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

public class CanvasMainActivity extends Activity {
	DrawingView dv;
	private Paint mPaint;
	public static final int MENU_NEW = Menu.FIRST;
	public static final int MENU_WRITE = Menu.FIRST + 9;
	public static final int MENU_ERASE = Menu.FIRST + 1;
	public static final int MENU_SAVE = Menu.FIRST + 2;
	public static final int MENU_EXIT = Menu.FIRST + 3;
	private static final String IMAGE_DIRECTORY_NAME = "SURVEY_ACESS";
	private IndicatorResultVO indicatorResultVO;
	private IndicatorResultVO tempIndicatorResultVO;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		System.gc();
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		tempIndicatorResultVO = (IndicatorResultVO) getIntent().getSerializableExtra("inResultVO");
		indicatorResultVO = Entity.query(IndicatorResultVO.class).where("indicatorId").eq(tempIndicatorResultVO.indicatorId+"").and("homeId").eq(tempIndicatorResultVO.homeId)
		.and("houseId").eq(tempIndicatorResultVO.houseId).execute();
		dv = new DrawingView(this);
		dv.setBackgroundColor(Color.WHITE);
		setContentView(dv);
		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setDither(true);
		mPaint.setColor(Color.BLUE);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);
		mPaint.setStrokeCap(Paint.Cap.ROUND);
		mPaint.setStrokeWidth(5);
		if(indicatorResultVO!=null && indicatorResultVO.comment_img!=null){
			byte[] decodedString = Base64.decode(indicatorResultVO.comment_img, Base64.DEFAULT);
			Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
			Drawable d = new BitmapDrawable(getResources(),bitmap);
			dv.setBackgroundDrawable(d);
		}
	}

	@Override
	public void onBackPressed() {
		// your code.
		AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
        builder1.setMessage(getString(R.string.quitwithoutsave_message));
        builder1.setCancelable(true);
        builder1.setPositiveButton(getString(R.string.homestay_sync_ok),new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
    			if (isSaveFile()) {
    				Toast.makeText(getApplicationContext(), "Save Complete", Toast.LENGTH_LONG).show();
    				CanvasMainActivity.this.finish();
    			}
    			
            }
        });
        builder1.setNegativeButton(getString(R.string.cancel_message),new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
                CanvasMainActivity.this.finish();
            }
        });
        AlertDialog alert11 = builder1.create();
        alert11.show();	         
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE,MENU_WRITE,Menu.NONE,getResources().getString(R.string.writing_write));
		menu.add(Menu.NONE, MENU_ERASE, Menu.NONE, getResources().getString(R.string.writing_erase));
		menu.add(Menu.NONE, MENU_NEW, Menu.NONE, getResources().getString(R.string.writing_new));
		menu.add(Menu.NONE, MENU_EXIT, Menu.NONE, getResources().getString(R.string.writing_exit));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			Intent i = new Intent(CanvasMainActivity.this,CanvasMainActivity.class);
			startActivity(i);
			finish();
			return true;
		case 2:
			mPaint.setColor(Color.WHITE);
			mPaint.setStyle(Paint.Style.STROKE);
			mPaint.setStrokeJoin(Paint.Join.ROUND);
			mPaint.setStrokeCap(Paint.Cap.ROUND);
			mPaint.setStrokeWidth(40);
			return true;
		case 3:
			if (isSaveFile()) {
				Toast.makeText(getApplicationContext(), "Save Complete", Toast.LENGTH_LONG).show();
			}
			return true;
		case 10:
			mPaint.setColor(Color.BLUE);
			mPaint.setStyle(Paint.Style.STROKE);
			mPaint.setStrokeJoin(Paint.Join.ROUND);
			mPaint.setStrokeCap(Paint.Cap.ROUND);
			mPaint.setStrokeWidth(5);
			return true;
		case 4:
			AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
	        builder1.setMessage(getString(R.string.quitwithoutsave_message));
	        builder1.setCancelable(true);
	        builder1.setPositiveButton(getString(R.string.homestay_sync_ok),new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int id) {
	                dialog.cancel();
	    			if (isSaveFile()) {
	    				Toast.makeText(getApplicationContext(), "Save Complete", Toast.LENGTH_LONG).show();
	    				CanvasMainActivity.this.finish();
	    			}
	    			
	            }
	        });
	        builder1.setNegativeButton(getString(R.string.cancel_message),new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int id) {
	                dialog.cancel();
	                CanvasMainActivity.this.finish();
	            }
	        });
	        AlertDialog alert11 = builder1.create();
	        alert11.show();	      
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public boolean isSaveFile() {
		//Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME
		File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
		boolean success = false;
		if (!folder.exists()) {
			success = folder.mkdirs();
		}

		System.out.println(success + "folder");

		File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/"+IMAGE_DIRECTORY_NAME+"/SampleFileName.jpg");

		if (!file.exists()) {
			try {
				success = file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		System.out.println(success + "file");

		FileOutputStream ostream = null;
		try {
			ostream = new FileOutputStream(file);

			System.out.println(ostream);
			View targetView = dv;

			// myDrawView.setDrawingCacheEnabled(true);
			// Bitmap save = Bitmap.createBitmap(myDrawView.getDrawingCache());
			// myDrawView.setDrawingCacheEnabled(false);
			// copy this bitmap otherwise distroying the cache will destroy
			// the bitmap for the referencing drawable and you'll not
			// get the captured view
			// Bitmap save = b1.copy(Bitmap.Config.ARGB_8888, false);
			// BitmapDrawable d = new BitmapDrawable(b);
			// canvasView.setBackgroundDrawable(d);
			// myDrawView.destroyDrawingCache();
			// Bitmap save = myDrawView.getBitmapFromMemCache("0");
			// myDrawView.setDrawingCacheEnabled(true);
			// Bitmap save = myDrawView.getDrawingCache(false);
			Bitmap well = dv.getBitmap();
			Bitmap save = Bitmap.createBitmap(320, 480, Config.ARGB_8888);
			Paint paint = new Paint();
			paint.setColor(Color.WHITE);
			Canvas now = new Canvas(save);
			now.drawRect(new Rect(0, 0, 320, 480), paint);
			now.drawBitmap(well,new Rect(0, 0, well.getWidth(), well.getHeight()),new Rect(0, 0, 320, 480), null);

			// Canvas now = new Canvas(save);
			// myDrawView.layout(0, 0, 100, 100);
			// myDrawView.draw(now);
			if (save == null) {
				System.out.println("NULL bitmap save\n");
			}
			save.compress(Bitmap.CompressFormat.PNG, 100, ostream);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
			save.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
			byte[] byteArray = byteArrayOutputStream .toByteArray();
			indicatorResultVO.comment_img =Base64.encodeToString(byteArray, Base64.DEFAULT);
			indicatorResultVO.save();
			// bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
			// ostream.flush();
			// ostream.close();
			return true;
		} catch (NullPointerException e) {
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "Null error",
					Toast.LENGTH_SHORT).show();
			return false;
		}

		catch (FileNotFoundException e) {
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "File error",
					Toast.LENGTH_SHORT).show();
			return false;
		}

		catch (IOException e) {
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "IO error",
					Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	public class DrawingView extends View {

		public int width;
		public int height;
		private Bitmap mBitmap;
		private Canvas mCanvas;
		private Path mPath;
		private Paint mBitmapPaint;
		Context context;
		private Paint circlePaint;
		private Path circlePath;

		public DrawingView(Context c) {
			super(c);
			context = c;
			mPath = new Path();
			mBitmapPaint = new Paint(Paint.DITHER_FLAG);
			circlePaint = new Paint();
			circlePath = new Path();
			circlePaint.setAntiAlias(true);
			circlePaint.setColor(Color.GREEN);
			circlePaint.setStyle(Paint.Style.STROKE);
			circlePaint.setStrokeJoin(Paint.Join.MITER);
			circlePaint.setStrokeWidth(4f);

		}

		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
			super.onSizeChanged(w, h, oldw, oldh);

			mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
			mCanvas = new Canvas(mBitmap);

		}

		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

			canvas.drawPath(mPath, mPaint);

			canvas.drawPath(circlePath, circlePaint);
		}

		private float mX, mY;
		private static final float TOUCH_TOLERANCE = 4;

		private void touch_start(float x, float y) {
			mPath.reset();
			mPath.moveTo(x, y);
			mX = x;
			mY = y;
		}

		private void touch_move(float x, float y) {
			float dx = Math.abs(x - mX);
			float dy = Math.abs(y - mY);
			if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
				mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
				mX = x;
				mY = y;

				circlePath.reset();
				circlePath.addCircle(mX, mY, 30, Path.Direction.CW);
			}
		}

		private void touch_up() {
			mPath.lineTo(mX, mY);
			circlePath.reset();
			// commit the path to our offscreen
			mCanvas.drawPath(mPath, mPaint);
			// kill this so we don't double draw
			mPath.reset();
		}

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			float x = event.getX();
			float y = event.getY();

			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				touch_start(x, y);
				invalidate();
				break;
			case MotionEvent.ACTION_MOVE:
				touch_move(x, y);
				invalidate();
				break;
			case MotionEvent.ACTION_UP:
				touch_up();
				invalidate();
				break;
			}
			return true;
		}

		public Bitmap getBitmap() {
			// this.measure(100, 100);
			// this.layout(0, 0, 100, 100);
			this.setDrawingCacheEnabled(true);
			this.buildDrawingCache();
			Bitmap bmp = Bitmap.createBitmap(this.getDrawingCache());
			this.setDrawingCacheEnabled(false);

			return bmp;
		}

		public void clear() {
			mBitmap.eraseColor(Color.GREEN);
			invalidate();
			System.gc();

		}
	}

}
